/**
 * Copyright (C) Octlan Corporation. All rights reserved.
 * 
 * @author todzhang
 * @date 2010-3-2
 * @version $Id: PeopleProvider.java 16 2010-03-05 07:39:04Z todzhang $
 */
package com.octlan.droid.mis.content;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;

import com.octlan.droid.mis.vo.People.Person;

public class PeopleProvider extends ContentProvider {
	// debugging support
	private static final String		TAG						= "PeopleProvider";

	// Table of database versions. Don't forget to update!
	// NOTE: The major version values are shifted left 8 bits (x 256),
	// so let the minor use the rights 8 bits(< 256).
	// If database struct changed, I increase major, or else keep it unchanged,
	// and set minor to 1.
	// If database meaning changed, I increse minor, or else keep it unchanged,
	// and keep major unchanged.
	private static final int		DATABASE_VERSION_MAJOR	= 1 * 256;
	private static final int		DATABASE_VERSION_MINOR	= 1;

	public static final String		PROVIDER_NAME			= "com.octlan.droid.mis.content.peopleprovider";
	public static final Uri			CONTENT_URI				= Uri.parse("content://" + PROVIDER_NAME + "/people");

	// general database configuration and tables
	private static final String		sDatabaseName			= "mis.db";
	final static String				TABLE_NAME				= "people";

	private static final int		PEOPLE					= 1;
	private static final int		PERSON_ID				= 2;

	private static final UriMatcher	uriMatcher;
	static {
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		uriMatcher.addURI(PROVIDER_NAME, "people", PEOPLE);
		uriMatcher.addURI(PROVIDER_NAME, "people/#", PERSON_ID);
	}

	private SQLiteOpenHelper		mOpenHelper				= null;
	private SQLiteDatabase			database				= null;

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// mOpenHelper.getWritableDatabase().delete(TABLE_NAME, "", selectionArgs);
		// return 0;
		int count = 0;
		switch (uriMatcher.match(uri)) {
		case PEOPLE:
			count = database.delete(TABLE_NAME, selection, selectionArgs);
			break;
		case PERSON_ID:
			String id = uri.getPathSegments().get(1);
			count = database.delete(TABLE_NAME, Person._ID + " = " + id
					+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	@Override
	public String getType(Uri uri) {
		switch (uriMatcher.match(uri)) {
		// ---get all people---
		case PEOPLE:
			return "vnd.android.cursor.dir/vnd.octlan.people";
			// ---get a particular person---
		case PERSON_ID:
			return "vnd.android.cursor.item/vnd.octlan.people";
		default:
			throw new IllegalArgumentException("Unsupported URI: " + uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// mOpenHelper.getWritableDatabase().insert(TABLE_NAME, "", values);
		// return null;
		// ---add a new person---
		long rowID = database.insert(TABLE_NAME, "", values);

		// ---if added successfully---
		if (rowID > 0) {
			Uri _uri = ContentUris.withAppendedId(CONTENT_URI, rowID);
			getContext().getContentResolver().notifyChange(_uri, null);
			return _uri;
		}
		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {
		mOpenHelper = new DatabaseHelper(getContext(), DATABASE_VERSION_MAJOR + DATABASE_VERSION_MINOR);
		if (mOpenHelper != null) {
			database = mOpenHelper.getWritableDatabase();
			return true;
		} else {
			return false;
		}
		// return (mOpenHelper == null) ? false : true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		// Cursor cur = mOpenHelper.getReadableDatabase().query(TABLE_NAME, projection, selection, null, null, null,
		// null);
		//		
		// Toast.makeText(this.getContext(), "test Cur!", Toast.LENGTH_SHORT);
		// return cur;

		SQLiteQueryBuilder sqlBuilder = new SQLiteQueryBuilder();
		sqlBuilder.setTables(TABLE_NAME);

		if (uriMatcher.match(uri) == PERSON_ID)
			// ---if getting a particular book---
			sqlBuilder.appendWhere(Person._ID + " = " + uri.getPathSegments().get(1));

		if (sortOrder == null || sortOrder == "")
			sortOrder = Person._ID;

		Cursor c = sqlBuilder.query(database, projection, selection, selectionArgs, null, null, sortOrder);

		// ---register to watch a content URI for changes---
		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		// mOpenHelper.getWritableDatabase().update(TABLE_NAME, values, selection, null);
		// return 0;
		int count = 0;
		switch (uriMatcher.match(uri)) {
		case PEOPLE:
			count = database.update(TABLE_NAME, values, selection, selectionArgs);
			break;
		case PERSON_ID:
			count = database.update(TABLE_NAME, values, Person._ID + " = " + uri.getPathSegments().get(1)
					+ (!TextUtils.isEmpty(selection) ? " AND (" + selection + ')' : ""), selectionArgs);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI " + uri);
		}
		getContext().getContentResolver().notifyChange(uri, null);
		return count;
	}

	private static class DatabaseHelper extends SQLiteOpenHelper {
		public DatabaseHelper(Context context, int newVersion) {
			super(context, sDatabaseName, null, newVersion);
		}

		@Override
		public void onCreate(SQLiteDatabase db) {
			StringBuilder builder = new StringBuilder();
			builder
					.append("CREATE TABLE people ( _id INTEGER PRIMARY KEY AUTOINCREMENT, _state INTEGER NOT NULL DEFAULT 0, name TEXT, pimage BLOB, pid INTEGER NOT NULL DEFAULT -1, number TEXT, motion TEXT, summary TEXT, _dirty INTEGER NOT NULL DEFAULT 0, _sync_mark INTEGER NOT NULL DEFAULT 0, _exists_on_server INTEGER NOT NULL DEFAULT 0, _altitude  REAL NOT NULL DEFAULT -1, _latitude REAL NOT NULL DEFAULT -1, _longitude REAL NOT NULL DEFAULT -1,_last_update INTEGER NOT NULL DEFAULT 0);");
			db.execSQL(builder.toString());
		}

		@Override
		public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
			Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
					+ ", which will destroy all old data");
			db.execSQL("DROP TABLE IF EXISTS people");
			onCreate(db);
		}
	}

}
